import jsCookie from 'js-cookie'
import { setToken } from '@/utils/storage'

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function formatCookies(cookieStr) {
  const allCookies = (cookieStr || '').split(';')
  const cookies = {}

  for (let i = 0; i < allCookies.length; i++) {
    const cookie = allCookies[i].trim().split('=')
    let cookieVal = cookie[1]
    if (cookie.length > 2) {
      for (let j = 0; j < cookie.length - 2; j++) {
        cookieVal += '='
      }
    }
    cookies[cookie[0]] = cookieVal
  }
  return cookies
}
